﻿using System.ComponentModel;
using System;
using System.Reflection;
using DeepEarth.Core.Utils;
namespace DeepEarth.Core.Converters
{
    public class TypeTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string typeString = value.ToString();
            Type t = null;

            // Detect whether value is fully qualified. If so, use Type.GetType. Otherwise, use the typeloader.
            if (typeString.Trim().ToLower().Contains("version="))
            {
                try
                {
                    // If we don't receive a fully qualified type string, this can throw an exception if the assembly has already been loaded
                    // TODO: Attempt to determine a fully qualified string before attempting the call on GetType
                    t = Type.GetType(typeString);
                }
                catch
                {
                }
            }

            if (t == null)
            {
                // Use the type loader, or parse the app manifest, get the assemblies, load the assemblies, interrogate each assembly for the type we need.
                t = TypeLoader.GetType(typeString);
            }

            return t;
        }
    }
}
